package indi.readbook.example.admin.controller.system;

import indi.readbook.example.admin.controller.BaseController;
import indi.readbook.example.admin.service.RoleService;
import indi.readbook.example.common.entity.system.RoleDO;
import indi.readbook.example.common.res.ViewResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/sys/role")
@RestController
public class RoleController extends BaseController {
	String prefix = "system/role";
	@Autowired
	RoleService roleService;

	@GetMapping()
	String role() {
		return prefix + "/role";
	}

	@GetMapping("/list")
	@ResponseBody()
	List<RoleDO> list() {
		List<RoleDO> roles = roleService.list();
		return roles;
	}

	@GetMapping("/add")
	String add() {
		return prefix + "/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id, Model model) {
		RoleDO roleDO = roleService.get(id);
		model.addAttribute("role", roleDO);
		return prefix + "/edit";
	}

	@PostMapping("/save")
	@ResponseBody()
	ViewResult save(RoleDO role) {
		if (roleService.save(role) > 0) {
			return ViewResult.success();
		} else {
			return ViewResult.error(1, "保存失败");
		}
	}

	@PostMapping("/update")
	@ResponseBody()
    ViewResult update(RoleDO role) {
		if (roleService.update(role) > 0) {
			return ViewResult.success();
		} else {
			return ViewResult.error(1, "保存失败");
		}
	}

	@PostMapping("/remove")
	@ResponseBody()
    ViewResult save(Long id) {
		if (roleService.remove(id) > 0) {
			return ViewResult.success();
		} else {
			return ViewResult.error(1, "删除失败");
		}
	}

	@PostMapping("/batchRemove")
	@ResponseBody
    ViewResult batchRemove(@RequestParam("ids[]") Long[] ids) {
		int r = roleService.batchremove(ids);
		if (r > 0) {
			return ViewResult.success();
		}
		return ViewResult.error();
	}
}
